import random
import re

import requests

# m3uUrl = "https://gitee.com/mytv-android/iptv-api/raw/master/output/result.m3u"
m3uUrl = "https://gh-proxy.com/https://raw.githubusercontent.com/Kimentanm/aptv/master/m3u/iptv.m3u"
# m3uUrl = "https://gh-proxy.com/https://raw.githubusercontent.com/mursor1985/LIVE/refs/heads/main/iptv.m3u"

_chrome_ua = [
	'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
	'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
	'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
]

m3uPath = './result.m3u'
txt_path = './ipv6.txt'


def get_m3u(url=m3uUrl):
	res = requests.get(url=url, headers={
		'User-Agent': random.choice(_chrome_ua)
	})
	# print(res.text)
	with open(m3uPath, "w", encoding="utf-8") as f:
		f.write(res.text)


def m3u_to_grouped_txt(m3u_path):
	# 存储分组结构 {group_name: [channel1, channel2, ...]}
	groups = {}
	current_group = "未分组"  # 默认分组名称
	current_channel = None

	# 正则表达式匹配分组和频道名
	group_pattern = re.compile(r'group-title="([^"]+)"', re.IGNORECASE)
	channel_pattern = re.compile(r',([^,]+)$')
	try:
		with open(m3u_path, "r", encoding="utf-8") as f:
			for line in f.readlines():
				line = line.strip()
				# 处理分组信息
				if line.startswith('#EXTINF'):
					# 查找分组信息
					group_match = group_pattern.search(line)
					if group_match:
						current_group = group_match.group(1)
					# 查找频道名称
					channel_match = channel_pattern.search(line)
					if channel_match:
						current_channel = channel_match.group(1).strip()
					else:
						# 如果无法提取频道名，使用默认值
						current_channel = f"频道_{len(groups.get(current_group, [])) + 1}"

				# 处理URL行
				elif line and not line.startswith('#'):
					if current_channel:
						# 添加到分组字典
						if current_group not in groups:
							groups[current_group] = []

						groups[current_group].append(f"{current_channel},{line}")
						current_channel = None  # 重置等待下一个频道

		# 写入TXT文件
		with open(txt_path, 'w', encoding='utf-8') as out:
			for group, channels in groups.items():
				# if not any(name in group for name in ['央视频道', '卫视频道', '动画频道', '经典剧场']):
				# if not any(name in group for name in ['央视频道', '卫视频道', '经典剧场']):
				if not any(name in group for name in ['央视', '卫视']):
					continue
				# 写入分组标题
				out.write(f"{group},#genre#\n")
				for channel in channels:
					url = channel.split(',', 1)[1]
					flag = test_url(url)
					if not flag:
						channels.remove(channel)
				# 写入该分组所有频道
				out.write("\n".join(channels))
				out.write("\n\n")

		print(f"转换成功！已保存到: {txt_path}")
		return True
	except Exception as e:
		print(f"转换失败: {str(e)}")
		return False


def test_url(url):
	try:
		response = requests.get(url, timeout=0.6)
		if response.status_code == 200 and '#EXTM3U' in response.text:
			print(f"直播源检测成功: {url}")
			return True
		else:
			print(f"直播源检测失败: {url}")
			return False
	except Exception as e:
		print(f"直播源检测错误: {e}, 链接: {url}")
		return False
